using NaughtyAttributes;
using SimpleJSON;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class ChatItemHelper : NodeHelper
    {
        public RectTransform rect;
        public RectTransform imageRect;
        public RectTransform textRect;
        public Text text;
        public int maxWidth;
        public int lineHeight;
        public int minHeight;
        public int offsetHeight;
        public float horizontalPadding;
        public float verticalPadding;
        [SelectRef(UIKey.DATA_KEY)] public SelectKey textKey;

        public override void SetData(JSONObject obj)
        {
            base.SetData(obj);
            BindData(textKey.Get(obj).Value);
        }

        protected override void BindData(string s)
        {
            text.text = s;
            float w = 0;
            float h = 0;
            var tg = text.cachedTextGeneratorForLayout;
            var settings = text.GetGenerationSettings(Vector2.zero);
            var width = tg.GetPreferredWidth(s, settings) / text.pixelsPerUnit;
            w = width > maxWidth ? maxWidth : width;
            h = width == 0 ? lineHeight : math.ceil(width / maxWidth) * lineHeight;

            textRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, w);
            textRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, h);

            imageRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, w + horizontalPadding * 2);
            imageRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, h + verticalPadding * 2);

            rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, GetHeight());
        }

        [Button]
        public void Refresh()
        {
            BindData(text.text);
        }

        [Button]
        public float GetHeight()
        {
            var height = imageRect.rect.height + offsetHeight;
            return height > minHeight ? height : minHeight;
        }

        public void Show()
        {
            gameObject.SetActive(true);
        }

        public void Hide()
        {
            gameObject.SetActive(false);
        }
    }
}